<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 采购设置
 * Class BookHomePurchaseSet
 * @package app\common\model
 */
class BookHomePurchaseSet extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'book_home_purchase_set';


    /**
     * 计算更改之后总金额
     * @param $total 总金额
     * @param $node 类型  增加还是减少金额   1增加   2减少
     * @param $money 本次增加或减少金额
     */
    public function countTotalMoney($total , $node , $money){
        if($node == 1){
            $finally = $total + $money;
        }else{
            $finally = $total - $money;
        }
        if((int)$finally < 0){
            throw new \Exception('减少金额不能大于剩余金额');
        }
        return $finally;
    }
    /**
     * 计算更改之前剩余金额
     * @param $total 总金额
     * @param $kind 种类 1   经费   2 邮费
     */
    public function countBeforeSurplusMoney($total , $kind = 1){
        $bookHomePurchaseMoney = $kind == 1 ? $this->getBookHomePurchaseMoney() : $this->getPostageMoney();
        $total -= $bookHomePurchaseMoney;
        return $total;
    }
    /**
     * 计算更改之后剩余金额
     * @param $total 总金额
     * @param $node 类型  增加还是减少金额   1增加   2减少
     * @param $money 本次增加或减少金额
     */
    public function countAfterSurplusMoney($total , $node , $money , $kind){
        $bookHomePurchaseMoney = $kind == 1 ? $this->getBookHomePurchaseMoney() : $this->getPostageMoney();
        $total -= $bookHomePurchaseMoney;
        if($node == 1){
            $finally = $total + $money;
        }else{
            $finally = $total - $money;
        }
        if((int)$finally < 0){
            throw new \Exception('减少金额不能大于剩余金额');
        }
        return $finally;
    }

    /**
     * 获取已采购经费金额
     */
    public function getBookHomePurchaseMoney(){
        $res = Shop::sum('purchase_money');
        return sprintf("%.2f" , $res);
    }
    /**
     * 获取已采购邮费金额
     */
    public function getPostageMoney(){
        $res = BookHomeOrder::where('payment' , 2)->where(function($query){
            $query->whereRaw(DB::raw('is_pay = 2 || is_pay = 6 || is_pay = 8'));
        })->sum('price');
        return sprintf("%.2f" , $res);
    }



}

